package com.demo.util;

import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: evildoer
 * @datetime: 2021/3/2 11:31
 */
public class FilterUtil{
    /**
     * @description: 模糊查找
     * @param condition 状态
     * @param target 筛选目标
     * @param list 数据集合
     * @param function 函数
     * @return: java.util.List<T>
     * @author: evildoer
     * @datetime: 2021/3/2 11:32
     */
    public static <T> List<T> listFilter(boolean condition, String target, List<T> list, Function<T, ?> function) {
        List<T> result = null;
        if (condition) {
            result = listFilter(target, list, function);
        }
        // 不满足条件直接返回原数据集合
        return Optional.ofNullable(result).orElse(list);
    }


    public static <T> List<T> listFilter(String target, List<T> list, Function<T, ?> function) {
        List<T> result = new LinkedList<>();
        //该处决定大小写是否敏感
        Pattern pattern = Pattern.compile(target, Pattern.CASE_INSENSITIVE);
        for (T t : list) {
            Matcher matcher = pattern.matcher(function.apply(t).toString());
            if (matcher.find()) {
                result.add(t);
            }
        }
        return result;
    }
}

